import { loginByUsername, getUserInfo } from '@/api/login'

import {getToken, setToken, removeToken} from '@/utils/auth.js'

const user = {
    state: {
        userName: '',
        competence: '',
        token: getToken()
    },
    mutations: {
        SET_USERNAME (state, userName) {
            state.userName = userName
        },
        SET_COMPETENCE (state, competence) {
            state.competence = competence
        },
        SET_TOKEN (state, token) {
            state.token = token
        }
    },
    actions:{
        // 用登录户名
        LoginByUsername({ commit }, userInfo) {
            let params = {
                userName: userInfo.userName.trim(),
                password: userInfo.password
            }
            return new Promise((resolve, reject) => {
              loginByUsername(params).then(response => {
                const data = response.data
                if(data.success){
                    setToken(data.token)
                    return resolve()
                }
                reject({success:false, code:2, message:'登录失败'})
              }).catch(error => {
                reject(error)
              })
            })
        },
        // 获取用户信息
        GetUserInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                getUserInfo().then(response => {
                    const data = response.data
                    if (data.success) { // 由于mockjs 不支持自定义状态码只能这样hack
                        commit('SET_COMPETENCE', data.result.competence)
                        commit('SET_USERNAME', data.result.userName)
                        return resolve(data)          
                    }
                    reject({success:false, code:2, message:'该用户不存在'})
                    
                }).catch(error => {
                    reject(error)
                })
            })
        },
    }
}

export default user